﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

// See "Dynamic Space Management for User Interfaces"
// by Blaine A. Bell and Steven K. Feiner:
// http://monet.cs.columbia.edu/publications/uist00.pdf
//
// and "Adaptive Multiple Texture Approach to Texture Packing for 3D Video Games" by
// Alexander Wong and Andrew Kennings:
// http://www.einfodaily.com/piTunez/p189-wong.pdf

namespace EngineOfEvermore.Common
{
    public class WhitespaceManager
    {
        const int LEFT = 0;
        const int TOP = 1;
        const int RIGHT = 2;
        const int BOTTOM = 3;

        List<Rectangle> _fullSpaceList = new List<Rectangle>();
        List<Rectangle> _largestEmptySpaceList = new List<Rectangle>();


        public WhitespaceManager( Size initialSize )
        {
            _largestEmptySpaceList.Add( new Rectangle( Point.Empty, initialSize ) );
        }

        public bool Insert( Size sz, out Rectangle output )
        {
            if ( _findInsertionPoint( sz, out output ) )
            {
                _addRectangle( output );
                return true;
            }

            return false;
        }
        
        void _addRectangle( Rectangle dstRect )
        {
            _fullSpaceList.Add( dstRect );

            Rectangle expandedRect = dstRect;
            expandedRect.Inflate( 1, 1 );

            IEnumerable<Rectangle> cList = 
                _largestEmptySpaceList.Where( r => expandedRect.IntersectsWith( r ) );

            List<Rectangle>[] possibleLESList = new List<Rectangle>[4];
            List<Rectangle>[] adjacentLESList = new List<Rectangle>[4];

            foreach ( Rectangle o in cList )
            {
                if ( !o.IntersectsWith( dstRect ) )
                {
                    adjacentLESList[_getAdjacencyDir( dstRect, o )].Add( o );
                }
                else
                {
                    _largestEmptySpaceList.Remove( o );

                    if ( o.Left < dstRect.Left )
                    {
                        possibleLESList[LEFT].Add( 
                            new Rectangle( o.Left,dstRect.Left,o.Top,o.Bottom ) 
                            );
                    }
                    
                    if ( o.Right > dstRect.Right )
                    {
                        possibleLESList[RIGHT].Add( 
                            new Rectangle( dstRect.Right,o.Right,o.Top,o.Bottom) 
                            );
                    }

                    if (o.Top < dstRect.Top )
                    {
                        possibleLESList[BOTTOM].Add( 
                            new Rectangle( o.Left,o.Right,o.Top,dstRect.Top ) 
                            );
                    }

                    if ( o.Bottom > dstRect.Bottom )
                    {
                        possibleLESList[TOP].Add( 
                            new Rectangle( o.Left, o.Right, dstRect.Bottom, o.Bottom ) 
                            );
                    }
                }
            }

            for ( int dir = LEFT; dir <= BOTTOM; ++dir )
            {
                foreach ( Rectangle emptySpace in possibleLESList[dir] )
                {
                    if ( !adjacentLESList[dir].Any( x => x.Contains( emptySpace ) ) &&
                         !possibleLESList[dir].Any( x => x.Contains( emptySpace ) )
                        )
                    {
                        _largestEmptySpaceList.Add( emptySpace );
                    }
                }
            }

            _largestEmptySpaceList.Sort( 
                ( a, b ) => (a.Width * a.Height).CompareTo( b.Width * b.Height ) 
                );
        }

        int _getAdjacencyDir( Rectangle rect, Rectangle adjacentRect )
        {
            if ( adjacentRect.Right < rect.Left )
            {
                return LEFT;
            }
            
            if ( adjacentRect.Left > rect.Right )
            {
                return RIGHT;
            }
            
            if ( adjacentRect.Bottom < rect.Top )
            {
                return TOP;
            }
            
            return BOTTOM;
        }

        bool _findInsertionPoint( Size sz, out Rectangle output )
        {
            foreach ( Rectangle r in _largestEmptySpaceList )
            {
                if ( r.Width >= sz.Width && r.Height >= sz.Height )
                {
                    output = new Rectangle( r.Location, sz );
                    return true;
                }
            }

            output = Rectangle.Empty;
            return false;
        }
    }
}
